package com.wenjing.xiaoyun.chat.controller;


import com.wenjing.xiaoyun.auth.config.UserAuthDetails;
import com.wenjing.xiaoyun.chat.agent.AgentContext;
import com.wenjing.xiaoyun.chat.agent.AgentEnum;
import com.wenjing.xiaoyun.chat.service.ChatSessionService;
import com.wenjing.xiaoyun.common.entity.ChatForm;
import com.wenjing.xiaoyun.common.entity.ChatSession;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@Tag(name = "小云助手")
@RestController
@RequestMapping("/xiaoyun")
public class XiaoyunController {

    private final AgentContext agentContext;


    private final ChatSessionService chatSessionService;

    public XiaoyunController(AgentContext agentContext, ChatSessionService chatSessionService) {
        this.agentContext = agentContext;
        this.chatSessionService = chatSessionService;
    }

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getDetails() instanceof UserAuthDetails userDetails) {
            return userDetails.getUserId();
        }
        return null;
    }

    @Operation(summary = "对话")
    @PostMapping("/chat")
    public Flux<String> chat(@RequestBody ChatForm chatForm) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Flux.error(new RuntimeException("用户未登录"));
        }
        return agentContext.chat(AgentEnum.XIAO_YUN_AGENT.getVale(), Long.valueOf(chatForm.getMemoryId()), chatForm.getMessage());
    }

    @Operation(summary = "获取会话列表")
    @GetMapping("/sessions")
    public List<ChatSession> getSessions() {
        Long userId = getCurrentUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        return chatSessionService.getUserSessions(userId);
    }

    @Operation(summary = "创建新会话")
    @PostMapping("/sessions")
    public ChatSession createSession(@RequestBody(required = false) ChatSession request) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        String sessionName = request != null && request.getSessionName() != null ?
                request.getSessionName() : "新对话";
        return chatSessionService.createSession(userId, sessionName);
    }

    @Operation(summary = "删除会话")
    @DeleteMapping("/sessions/{sessionId}")
    public void deleteSession(@PathVariable Long sessionId) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        chatSessionService.deleteSession(sessionId, userId);
    }

    @Operation(summary = "重命名会话")
    @PutMapping("/sessions/{sessionId}")
    public ChatSession renameSession(@PathVariable Long sessionId, @RequestBody ChatSession request) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        return chatSessionService.updateSessionName(sessionId, userId, request.getSessionName());
    }
}